package com.mxf.agricultural.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mxf.agricultural.common.BaseResponse;
import com.mxf.agricultural.common.DeleteRequest;
import com.mxf.agricultural.common.ErrorCode;
import com.mxf.agricultural.common.ResultUtils;
import com.mxf.agricultural.exception.BusinessException;
import com.mxf.agricultural.exception.ThrowUtils;
import com.mxf.agricultural.model.dto.order.OrderAddRequest;
import com.mxf.agricultural.model.dto.order.OrderEditRequest;
import com.mxf.agricultural.model.dto.order.OrderQueryRequest;
import com.mxf.agricultural.model.dto.order.OrderUpdateRequest;
import com.mxf.agricultural.model.entity.Order;
import com.mxf.agricultural.model.entity.User;
import com.mxf.agricultural.service.OrderService;
import com.mxf.agricultural.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 商品接口
 *
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Resource
    private OrderService orderService;

    @Resource
    private UserService userService;

    /**
     * 创建
     *
     * @param orderAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addOrder(@RequestBody OrderAddRequest orderAddRequest, HttpServletRequest request) {
        if (orderAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Order order = new Order();
        BeanUtils.copyProperties(orderAddRequest, order);

        orderService.validOrder(order, true);

        boolean result = orderService.save(order);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        User payerUser = userService.getById(orderAddRequest.getPayerid());
        User payerUserNew = new User();
        payerUserNew.setId(payerUser.getId());
        payerUserNew.setBalance(payerUser.getBalance() - order.getPrice()* order.getNum());
        boolean resultNew = userService.updateById(payerUserNew);


        User payeeUser = userService.getById(orderAddRequest.getPayeeid());
        User payeeUserNew = new User();
        payeeUserNew.setId(payeeUser.getId());
        payeeUserNew.setBalance(payeeUser.getBalance() + order.getPrice()* order.getNum());
        boolean resultNew2 = userService.updateById(payeeUserNew);

        long newOrderId = order.getId();
        return ResultUtils.success(newOrderId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteOrder(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        Order oldOrder = orderService.getById(id);
        ThrowUtils.throwIf(oldOrder == null, ErrorCode.NOT_FOUND_ERROR);

        boolean b = orderService.removeById(id);
        return ResultUtils.success(b);
    }

    @PostMapping("/update")
    public BaseResponse<Boolean> updateCommodity(@RequestBody CommodityUpdateRequest commodityUpdateRequest) {
        if (commodityUpdateRequest == null || commodityUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Commodity commodity = new Commodity();
        BeanUtils.copyProperties(commodityUpdateRequest, commodity);

        // 参数校验
        commodityService.validCommodity(commodity, false);
        long id = commodityUpdateRequest.getId();
        // 判断是否存在
        Commodity oldCommodity = commodityService.getById(id);
        ThrowUtils.throwIf(oldCommodity == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = commodityService.updateById(commodity);
        return ResultUtils.success(result);
    }
    /**
     * 分页获取列表
     *
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Commodity>> listCommodityByPage(@RequestBody CommodityQueryRequest commodityQueryRequest) {
        long current = commodityQueryRequest.getCurrent();
        long size = commodityQueryRequest.getPageSize();
        Page<Commodity> commodityPage = commodityService.page(new Page<>(current, size),
                commodityService.getQueryWrapper(commodityQueryRequest));
        return ResultUtils.success(commodityPage);
    }

    /**
     * 编辑（用户）
     *
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editCommodity(@RequestBody CommodityEditRequest commodityEditRequest, HttpServletRequest request) {
        if (commodityEditRequest == null || commodityEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Commodity commodity = new Commodity();
        BeanUtils.copyProperties(commodityEditRequest, commodity);

        // 参数校验
        commodityService.validCommodity(commodity, false);
        User loginUser = userService.getLoginUser(request);
        long id = commodityEditRequest.getId();
        // 判断是否存在
        Commodity oldCommodity = commodityService.getById(id);
        ThrowUtils.throwIf(oldCommodity == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldCommodity.getUserid().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = commodityService.updateById(commodity);
        return ResultUtils.success(result);
    }

}
